package org.whmmm.util.office;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.whmmm.util.office.inter.ExcelRowHandler;
import org.whmmm.util.office.util.ExcelReaderUtils;
import org.whmmm.util.office.util.PoiExcelUtil;

import java.io.IOException;
import java.util.*;

/**
 * <b>逐行处理 poi </b> <br/>
 * poi 3.17 <br/>
 * <br/><br/>
 * 创建时间: 2020/5/14 20:30
 *
 * @author whmmm
 */
public class ExcelRowReader {

    /**
     * 逐行处理 excel
     *
     * @param filePath
     * @param activeSheetIndex
     * @param headerIndex
     * @param handler
     */
    public static void read(String filePath, int activeSheetIndex, int headerIndex, ExcelRowHandler handler) {
        Workbook book = PoiExcelUtil.getWorkBook(filePath);


        try {

            if (book == null) {
                return;
            }
            Map<String, String> rowMap = null;

            Sheet sheet = book.getSheetAt(activeSheetIndex);
            List<String> header = new ArrayList<String>();
            Iterator<Row> iterator = sheet.iterator();
            while (iterator.hasNext()) {
                Row r = iterator.next();

                int rowNum = r.getRowNum();
                if (rowNum < headerIndex) {
                    // do nothing , skip
                } else if (rowNum == headerIndex) {
                    int number = r.getPhysicalNumberOfCells();
                    for (int i = 0; i < number; i++) {
                        header.add(ExcelReaderUtils.getCellFormatValue(r.getCell(i)));
                    }

                } else {
                    // if (rowNum > headerIndex)
                    rowMap = new LinkedHashMap<String, String>();
                    for (int i = 0; i < header.size(); i++) {
                        rowMap.put(header.get(i), ExcelReaderUtils.getCellFormatValue(r.getCell(i)));

                    }
                    handler.handle(r.getRowNum(), rowMap);
                }

            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (book != null) {
                try {
                    book.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    public static void read(String filePath, int headerIndex, ExcelRowHandler handler) {
        read(filePath, 0, headerIndex, handler);
    }

    public static void read(String filePath, ExcelRowHandler handler) {
        read(filePath, 0, 0, handler);
    }
}
